package com.base.commons.elasticsearch.service.impl;

import com.base.commons.elasticsearch.dao.EsBaseDao;
import com.base.commons.elasticsearch.utils.ElasticsearchIndexUtil;
import com.base.commons.tools.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.frameworkset.elasticsearch.entity.ESDatas;
import org.frameworkset.elasticsearch.entity.MapRestResponse;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public abstract class EsBranchIndexServiceImpl<M extends EsBaseDao<T>, T, D> extends EsCrudServiceImpl<M, T, D>{
    private String[] fieldNames;

    @Override
    public String[] exportCsvScrollDynamicTitle(String csvPathId, Object dto, Long size, Long pageSize, Class source, List dynamicHeader) throws Exception{
        return super.exportCsvScrollDynamicTitle(csvPathId, dto, size, pageSize, source, dynamicHeader);
    }

    public abstract String[] getBranchIndexField();
    public EsBranchIndexServiceImpl() {
        fieldNames = getBranchIndexField();
        if (ArrayUtils.isEmpty(fieldNames)) {
            throw new NullPointerException("fieldNames must not null");
        }
        if (fieldNames.length !=2) {
            throw new IllegalStateException("fieldNames.length must = 2");
        }
    }

    private String getBranchIndexName(Map paramMap) {
        String indexName = getIndexName();
        Date startTime = DateUtils.parse(String.valueOf(paramMap.get(fieldNames[0])), DateUtils.DATE_PATTERN_YYYY_MM);
        Date endTime = DateUtils.parse(String.valueOf(paramMap.get(fieldNames[1])), DateUtils.DATE_PATTERN_YYYY_MM);
        String[] indexNameArr = ElasticsearchIndexUtil.generateElasticsearchIndex(indexName, startTime, endTime);
        String indexNames = Arrays.stream(indexNameArr).collect(Collectors.joining(","));
        return indexNames;
    }
    @Override
    public long selectCount(Map paramMap) {
        String branchIndexName = getBranchIndexName(paramMap);
        MapRestResponse search = baseDao.search(branchIndexName + "/_count" + "?ignore_unavailable=true", COUNT, paramMap);
        return  search.getCount();
    }

    @Override
    public ESDatas searchList(Map paramMap) {
        String branchIndexName = getBranchIndexName(paramMap);
        return (ESDatas<T>) baseDao.searchList(branchIndexName+_SEARCH+"?ignore_unavailable=true",
                SEARCH_PAGING_DATA,
                paramMap,
                entityClass);
    }

    @Override
    public ESDatas searchListScroll(Map paramMap) {
        String branchIndexName = getBranchIndexName(paramMap);
        return  (ESDatas<T>) baseDao.searchList(branchIndexName+_SEARCH+"?scroll=10m&ignore_unavailable=true",
                SCROLL_DEFAULT_QUERY,
                paramMap,
                entityClass);
    }
}
